package com.wrx.club_management_backend.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;
/* 分布式锁 */
public class SimpleRedisLock implements ILock{

    /* 锁的名称 */
    private String name;

    private final static String PREFIX = "lock:";

    /* 线程标识前缀 */
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    private static final DefaultRedisScript<Long> TRY_LOCK_SCRIPT;

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        TRY_LOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        TRY_LOCK_SCRIPT.setLocation(new ClassPathResource("trylock.lua"));
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        TRY_LOCK_SCRIPT.setResultType(Long.class);
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    /* 默认是 时间单位是 毫秒*/
    private long timeSecOut;

    private TimeUnit unit;

    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(
            String name,
            StringRedisTemplate stringRedisTemplate,
            long timeSecOut,
            TimeUnit unit) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
        this.timeSecOut = timeSecOut;
        this.unit = unit;
    }


    @Override
    public boolean tryLock() {
        String key = PREFIX + name;
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        // 使用Lua脚本获取锁
        Long result = stringRedisTemplate.execute(
                TRY_LOCK_SCRIPT,
                Collections.singletonList(key), /*KEY*/
                threadId, String.valueOf(unit.toSeconds(timeSecOut)) /*ARGV*/
        );
        return result != null && result == 1L;
    }

    @Override
    public void unLock() {
        String key = PREFIX + name;
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        // 使用Lua脚本释放锁
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(key), /*KEY*/
                threadId /*ARGV*/
        );
    }
}